﻿#pragma once

#include <cstdint>
#include <thread>
#include <chrono>
#include "../corelib/time_util.hh"

namespace kratos { namespace engine {

// Frame delayer
class FrameDelayer {
public:
    // ctor
    // @param frame The frame of main cycle (frame/second)
    FrameDelayer(int frame);
    // dtor
    ~FrameDelayer();
    // frame start
    void beginFrame(std::time_t now = 0);
    // frame end
    void endFrame(std::time_t now = 0);

private:
    // Make the cycle slow down
    void tryDelay();

private:
    uint64_t frameInMillions_;
    uint64_t feedback_;
    uint64_t begin_;
    uint64_t end_;
    uint64_t overwork_;

private:
    static const uint32_t CPU_TIME_SLICE     = 10;   // The slice of CPU
    static const uint32_t OVERWORK_THRESHOLD = 5;    // Overwork threshold
    static const uint32_t DEFAULT_FRAME      = 60;   // Frame frequency by default
    static const uint32_t MILLION_RESOLUTION = 1000;
    static const uint32_t DELTA_MAX          = 100;
};

}}
